<template>
  <view class="login-page">
    <!-- 背景波浪效果 -->
    <view class="wave-box">
      <view class="wave wave-1"></view>
      <view class="wave wave-2"></view>
    </view>
    
    <view class="login-container">
      <view class="login-header">
        <image class="login-logo" src="/static/5G.png" mode="aspectFit"></image>
        <view class="login-title">战客清单营销工具</view>
        <view class="login-subtitle">平凉移动政企事业部专属工具</view>
      </view>
      
      <view class="login-form">
        <view class="input-group" :class="{'error': phoneError}">
          <u-icon name="phone" size="24" color="#007aff"></u-icon>
          <u-input 
            v-model="phone" 
            placeholder="请输入手机号" 
            type="number" 
            maxlength="11"
            clearable
            @input="validatePhone"
          ></u-input>
        </view>
        <view class="error-tip" v-if="phoneError">{{phoneErrorMsg}}</view>
        
        <view class="input-group" :class="{'error': passwordError}">
          <u-icon name="lock" size="24" color="#007aff"></u-icon>
          <u-input 
            v-model="password" 
            placeholder="请输入密码" 
            type="password"
            password
            clearable
            @input="validatePassword"
          ></u-input>
        </view>
        <view class="error-tip" v-if="passwordError">{{passwordErrorMsg}}</view>
        
        <u-button type="primary" class="login-btn" :loading="loading" @click="handleLogin">登录</u-button>
      </view>
      
      <view class="login-footer">
        <text>绿色通道 · 品质服务 · 创新拓展</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      phone: "",
      password: "",
      phoneError: false,
      phoneErrorMsg: "",
      passwordError: false,
      passwordErrorMsg: "",
      loading: false
    };
  },
  methods: {
    validatePhone() {
      if (!this.phone) {
        this.phoneError = true;
        this.phoneErrorMsg = "请输入手机号";
        return false;
      }
      // 简单的手机号验证：11位数字
      const phoneReg = /^1\d{10}$/;
      if (!phoneReg.test(this.phone)) {
        this.phoneError = true;
        this.phoneErrorMsg = "请输入有效的手机号";
        return false;
      }
      this.phoneError = false;
      return true;
    },
    
    validatePassword() {
      if (!this.password) {
        this.passwordError = true;
        this.passwordErrorMsg = "请输入密码";
        return false;
      }
      // 基础密码验证：至少5位
      if (this.password.length < 5) {
        this.passwordError = true;
        this.passwordErrorMsg = "密码长度不能少于5位";
        return false;
      }
      this.passwordError = false;
      return true;
    },
    
    validateForm() {
      const phoneValid = this.validatePhone();
      const passwordValid = this.validatePassword();
      return phoneValid && passwordValid;
    },
    
    // 检查密码状态
    checkPasswordStatus() {
      return new Promise((resolve, reject) => {
        this.$http.sendRequest('zhanke/user/check_password_status', 'POST', {
          phone: this.phone
        }).then(res => {
          if (res.data && res.data.code === 200) {
            resolve(res.data.data);
          } else {
            reject(res.data.msg || '检查密码状态失败');
          }
        }).catch(err => {
          reject(err.errMsg || '网络请求失败');
        });
      });
    },
    
    // 登录
    handleLogin() {
      if (!this.validateForm()) {
        return;
      }
      
      // 防止重复点击
      if (this.loading) {
        return;
      }
      
      this.loading = true;
      
      // 模拟登录过程
      uni.showLoading({
        title: "登录中..."
      });

      let url = 'zhanke/user/login';
      let data = {
        phone: this.phone,
        password: this.password,
        type: "战客"
      };
      console.log('请求参数---', data);

      this.$http.sendRequest(url, 'POST', data).then(res => {
        console.log('登录请求结果', res);
        
        if (res.data && res.data.code == 200) {
          const responseData = res.data.data;
          const token = responseData.token_type + ' ' + responseData.access_token;
          
          console.log('生成token:', token);
          
          // 存储token
          uni.setStorageSync('token', token);
          
          // 存储用户信息
          const userInfo = {
            id: responseData.user_info?.id || null,
            name: responseData.user_info?.name || "未知用户",
            phone: this.phone,
            department: responseData.user_info?.department || "平凉政企事业部"
          };
          uni.setStorageSync('userInfo', JSON.stringify(userInfo));
          
          // 检查密码状态
          this.checkPasswordStatus().then(passwordStatus => {
            uni.hideLoading();
            this.loading = false;
            
            console.log('密码状态检查结果:', passwordStatus);
            
            // 检查是否需要强制修改密码
            if (passwordStatus.isDefaultPassword) {
              uni.showToast({
                title: "登录成功，请修改密码",
                icon: "success",
                duration: 1500,
                success: () => {
                  setTimeout(() => {
                    uni.navigateTo({
                      url: '/pages/login/change-password?forced=true'
                    });
                  }, 1500);
                }
              });
            } else {
              uni.showToast({
                title: "登录成功",
                icon: "success",
                duration: 1500,
                success: () => {
                  setTimeout(() => {
                    uni.switchTab({ url: '/pages/business/index' });
                  }, 1500);
                }
              });
            }
          }).catch(err => {
            console.error('密码状态检查失败', err);
            uni.hideLoading();
            this.loading = false;
            
            // 即使检查失败，也正常进入系统
            uni.showToast({
              title: "登录成功",
              icon: "success",
              duration: 1500,
              success: () => {
                setTimeout(() => {
                  uni.switchTab({ url: '/pages/business/index' });
                }, 1500);
              }
            });
          });
        } else {
          uni.hideLoading();
          this.loading = false;
          
          uni.showToast({
            title: res.data?.msg || "登录失败",
            icon: "error",
            duration: 2000
          });
        }
      }).catch(err => {
        console.error('登录请求失败', err);
        uni.hideLoading();
        this.loading = false;
        
        uni.showToast({
          icon: "error",
          title: err.errMsg || "网络请求失败",
          duration: 2000
        });
      });
    }
  }
};
</script>

<style>
.login-page {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: #f5f7fa;
  position: relative;
  overflow: hidden;
}

/* 波浪背景 */
.wave-box {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.wave {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 200%;
  height: 80%;
  background: rgba(0, 122, 255, 0.08);
  border-radius: 43%;
}

.wave-1 {
  animation: wave 20s linear infinite;
  z-index: 1;
}

.wave-2 {
  animation: wave 15s linear infinite;
  z-index: 0;
  background: rgba(0, 122, 255, 0.05);
  bottom: -10%;
}

@keyframes wave {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.login-container {
  width: 85%;
  padding: 35px 25px;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.08);
  position: relative;
  z-index: 10;
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 35px;
}

.login-logo {
  width: 90px;
  height: 90px;
  margin-bottom: 15px;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}

.login-title {
  font-size: 26px;
  color: #333;
  font-weight: bold;
  letter-spacing: 1px;
  margin-bottom: 6px;
}

.login-subtitle {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.login-form {
  padding: 0 10px;
}

.input-group {
  display: flex;
  align-items: center;
  padding: 14px 16px;
  margin-bottom: 20px;
  background-color: #f8f9fa;
  border-radius: 10px;
  border: 1px solid #eaeaea;
  transition: all 0.3s ease;
}

.input-group.error {
  border-color: #fa3534;
  background-color: rgba(250, 53, 52, 0.05);
}

.input-group:focus-within {
  border-color: #007aff;
  box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.1);
}

.error-tip {
  color: #fa3534;
  font-size: 12px;
  padding-left: 10px;
  margin-top: -15px;
  margin-bottom: 15px;
}

u-icon {
  margin-right: 12px;
}

u-input {
  flex: 1;
  border: none;
  background: transparent;
  padding: 0;
  font-size: 16px;
}

.login-btn {
  width: 100%;
  height: 52px;
  margin-top: 15px;
  background: linear-gradient(135deg, #007aff, #0056b3);
  border-radius: 10px;
  font-size: 18px;
  font-weight: 500;
  letter-spacing: 2px;
  box-shadow: 0 5px 15px rgba(0, 122, 255, 0.3);
  transition: all 0.3s ease;
}

.login-btn:active {
  transform: translateY(3px);
  box-shadow: 0 2px 5px rgba(0, 122, 255, 0.3);
}

.login-footer {
  text-align: center;
  margin-top: 30px;
  font-size: 12px;
  color: #999;
}
</style> 